<template>
  <el-config-provider :size="getGlobalComponentSize" :locale="getGlobalI18n">
    <div v-show="setLockScreen">
      <router-view />
    </div>
  </el-config-provider>
</template>

<script setup lang="ts" name="app">
import { computed, ref, onBeforeMount, onMounted, onUnmounted, nextTick, watch, getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { storeToRefs } from 'pinia'
import { useThemeConfig } from '@renderer/stores/themeConfig'
import { Local } from '@renderer/utils/storage'
import setIntroduction from '@renderer/utils/setIconfont'
import { useConfigStore } from '@renderer/stores/configStore'
import { useGenerationStore } from './stores/useGenerationStore'
import { debounce } from 'lodash'
import { useModelStore } from './stores/useModelStore'
import { ipcService } from './services/ipcService'
import { useExPrompt } from './stores/useExPrompt'

const router = useRouter()
const instance = getCurrentInstance()!;
const $nodeInfo = instance?.appContext.config.globalProperties.$nodeInfo;
const $eventBus = instance?.appContext.config.globalProperties.$eventBus;
// 定义变量内容
const { messages, locale } = useI18n()
const storesThemeConfig = useThemeConfig()
const { themeConfig } = storeToRefs(storesThemeConfig)
const configStore = useConfigStore()
const generationStore = useGenerationStore()
const modelStore = useModelStore()
const expromptStore = useExPrompt();

const combinedPrompt = computed(() => generationStore.combinedPrompt);
const loraJson = computed(()=> expromptStore.loraListJson);
// 设置锁屏时组件显示隐藏
const setLockScreen = computed(() => {
  // 防止锁屏后，刷新出现不相关界面
  return themeConfig.value.isLockScreen
    ? themeConfig.value.lockScreenTime > 1
    : themeConfig.value.lockScreenTime >= 0
})

// 获取全局 i18n
const getGlobalI18n = computed(() => {
  return messages.value[locale.value]
})

/*
const debouncedSendPrompt = debounce((prompt: string) => {
  if (prompt) {
    ipcService.sendWebsocketData({prompt:prompt},'PROMPT_UPDATE');
  }
}, 500);

const debouncedSendLoras = debounce((loraJson: string)=>{
  if (loraJson){
    ipcService.sendWebsocketData({loraJson:loraJson},'LORA_UPDATE');
  }
},500)
*/



const debouncedUpdateNodeText = debounce((nodeId:string,text:string)=>{
  if (text && $eventBus && $nodeInfo.nodeId) {
      $eventBus.emit('update-text', {
        nodeId: nodeId,
        text: text
      });
  } else {
    // 调试用：打印未定义的原因
    if (!instance) console.error('Vue 实例未获取到');
    if (!instance?.appContext.config.globalProperties.$eventBus) console.error('$eventBus 未定义');
    if (!window.eventBus) console.error('window.eventBus 未定义（事件总线未初始化）');
  }
},500)

const debouncedUpdateNodeLora = debounce((nodeId:string,loraJson: string)=>{
  if (loraJson && $eventBus && $nodeInfo.nodeId) {
      $eventBus.emit('update-lora', {
        nodeId: nodeId,
        text: loraJson
      });
  } else {
    // 调试用：打印未定义的原因
    if (!instance) console.error('Vue 实例未获取到');
    if (!instance?.appContext.config.globalProperties.$eventBus) console.error('$eventBus 未定义');
    if (!window.eventBus) console.error('window.eventBus 未定义（事件总线未初始化）');
  }
},500)

watch(() => combinedPrompt, (val) => {
  if(val){
    if (val && $nodeInfo?.nodeId) {
      debouncedUpdateNodeText($nodeInfo.nodeId, val.value);
    }
  }
},{deep: true})

watch(() => loraJson, (val) => {
  if(val){
    if (val && $nodeInfo?.nodeId) {
      debouncedUpdateNodeLora($nodeInfo.nodeId, val.value);
    }
  }
},{deep: true})

// 设置初始化，防止刷新时恢复默认
onBeforeMount(() => {
  // 设置批量第三方 icon 图标
  setIntroduction.cssCdn()
  // 设置批量第三方 js
  setIntroduction.jsCdn()
})
// 页面加载时
onMounted( () => {
  nextTick(() => {
    // 获取缓存中的布局配置
    if (Local.get('themeConfig')) {
      storesThemeConfig.setThemeConfig({ themeConfig: Local.get('themeConfig') })
      document.documentElement.style.cssText = Local.get('themeConfigStyle')
      locale.value = Local.get('themeConfig').globalI18n;
    }
    const body = document.documentElement as HTMLElement;
    if (themeConfig.value.isIsDark) body.setAttribute('data-theme', 'dark');
    else body.setAttribute('data-theme', '');
    generationStore.loadConfig()
    configStore.loadConfig()
    configStore.delayLoadConfig();
    modelStore.fetchModels()
    router.push('/');
  })
})

</script>
